package util.bio.annotation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import util.gen.IO;

public class Bed extends Coordinate{

	//fields
	private String name;
	private double score; 
	private char strand;
	
	//constructor
	public Bed (String chromosome, int start, int stop, String name, double score, char strand){
		super(chromosome, start, stop);
		this.name = name;
		this.score = score;
		this.strand = strand;
	}

	//methods
	/**Parses a tab delimited bed file: chrom, start, stop, name, score, strand. Only the first three are required.
	 * @param subStart - bases to be subtracted from region starts
	 * @param subEnd - bases to be subtracted from region ends
	 * */
	public static Bed[] parseFile(File bedFile, int subStart, int subEnd){
		Bed[] bed =null;
		try{
			BufferedReader in = IO.fetchBufferedReader(bedFile);
			String line;
			String[] tokens;
			ArrayList<Bed> al = new ArrayList<Bed>();
			//chrom, start, stop, name, score, strand
			//0       1       2     3     4      5
			while ((line = in.readLine()) !=null) {
				line = line.trim();
				if (line.length() ==0 || line.startsWith("#")) continue;
				tokens = line.split("\\s+");
				if (tokens.length < 3) continue;
				String name = "";
				double score = 0;
				char strand = '.';
				if (tokens.length >= 6) {
					name = tokens[3];
					score = Double.parseDouble(tokens[4]);
					strand = tokens[5].charAt(0);
				}
				else if (tokens.length == 5){
					name = tokens[3];
					score = Double.parseDouble(tokens[4]);
				}
				else if (tokens.length == 4){
					name = tokens[3];
				}
				al.add(new Bed(tokens[0], Integer.parseInt(tokens[1])-subStart, Integer.parseInt(tokens[2])- subEnd, name, score, strand));
			}
			bed = new Bed[al.size()];
			al.toArray(bed);
		}catch (IOException e){
			e.printStackTrace();
		}
		return bed;
	}
	public String toString(){
		return chromosome+"\t"+start+"\t"+stop+"\t"+name+"\t"+score+"\t"+strand;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public char getStrand() {
		return strand;
	}

	public void setStrand(char strand) {
		this.strand = strand;
	}
}
